#include <SDL.h>
#include <SDL_opengl.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
	cout << "Initializing SDL." << endl;
	/* Initialize defaults, Video and Audio */
	if ((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1)) {
		cout << "Could not initialize SDL: " << SDL_GetError() << endl;
		exit(-1);
	}
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_Surface *screen = SDL_SetVideoMode(640, 480, 16, SDL_OPENGL/* | SDL_FULLSCREEN*/);
	if (!screen) {
		cout << "Unable to set video mode: " <<  SDL_GetError() << endl;
		return 1;
	}
	glClearColor(0, 0, 0, 0);
	glEnable(GL_TEXTURE_2D);
	glViewport(0, 0, 640, 480);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 640, 480, 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	GLuint texture[2];
	SDL_Surface *surface;
	if ((surface = SDL_LoadBMP("image.bmp"))) {
		if ((surface->w & (surface->w - 1)) != 0) {
			cout << "warning: image.bmp's width is not a power of 2" << endl;
		}
		if ((surface->h & (surface->h - 1)) != 0) {
			cout << "warning: image.bmp's height is not a power of 2" << endl;
		}
		glGenTextures(2, texture);
		cout << "texture id " << texture[0] << endl;
		cout << "texture id " << texture[1] << endl;
		glBindTexture(GL_TEXTURE_2D, texture[0]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, surface->w, surface->h, 0, GL_BGR, GL_UNSIGNED_BYTE, surface->pixels);
	} else {
		cout << "SDL could not load image.bmp: " << SDL_GetError() << endl;
		SDL_Quit();
		return 1;
	}
	if (surface) {
		SDL_FreeSurface(surface);
	}
	SDL_Event event;
	bool quit = false;
	while(!quit) {
		while(SDL_PollEvent(&event)) {
			switch(event.type) {
				case SDL_VIDEORESIZE:
					break;
				case SDL_QUIT:
					quit = true;
					break;
				default:
					break;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT);
		glBindTexture(GL_TEXTURE_2D, texture[0]);
		glBegin(GL_QUADS);
			glTexCoord2i(0, 0);
			glVertex3f(100, 100, 0);
			glTexCoord2i(1, 0);
			glVertex3f(228, 100, 0);
			glTexCoord2i(1, 1);
			glVertex3f(228, 228, 0);
			glTexCoord2i(0, 1);
			glVertex3f(100, 228, 0);
		glEnd();
		SDL_GL_SwapBuffers();
	};
	//SDL_Delay(3000);
	glDeleteTextures(2, texture);
	/* Shutdown all subsystems */
	SDL_Quit();
	cout << "Quiting..." << endl;
	return 0;
}
